package web

import (
	"gitee.com/youkelike/zlog"
	"gitee.com/youkelike/zvalidation"
	userv1 "gitee.com/youkelike/zvalidation/example/api/proto/gen/user/v1"
	"gitee.com/youkelike/zvalidation/example/domain"
	"gitee.com/youkelike/zvalidation/example/service"
	"gitee.com/youkelike/zvalidation/ginx"
	"github.com/gin-gonic/gin"
)

// Handler 处理博客模块的请求.
type UserHandler struct {
	svc service.UserService
	// 启动服务的时候创建了一个全局的 Validator 实例.
	val *zvalidation.Validator
	l   zlog.Logger
}

// NewHandler 创建新的 Handler 实例.
func NewUserHandler(l zlog.Logger, svc service.UserService, val *zvalidation.Validator) *UserHandler {
	return &UserHandler{
		svc: svc,
		val: val,
		l:   l,
	}
}

func (h *UserHandler) RegisterRoutes(server *gin.Engine) {
	server.POST("/api/v1/users", ginx.WrapBody[userv1.CreateUserRequest](h.l, h.val.ValidateCreateUserRequest, h.CreateUser))
}

func (h *UserHandler) CreateUser(c *gin.Context, req *userv1.CreateUserRequest) (ginx.Result, error) {
	err := h.svc.Create(c.Request.Context(), toUserDomain(req))
	if err != nil {
		return ginx.Result{}, err
	}
	return ginx.Result{Code: ginx.CodeSuccess, Msg: "created"}, nil
}

func toUserDomain(req *userv1.CreateUserRequest) domain.User {
	return domain.User{
		Username: req.Username,
		Password: req.Password,
		Email:    req.Email,
		Nickname: req.Nickname,
		Phone:    req.Phone,
	}
}
